<template>
  <div style="width: 1300px ;overflow: hidden;">
    <div style="margin-top: 10px;display: inline-block">
      <div style="height: 10px;width: 110px;
       display: inline-block;margin-left: 10px;margin-top: 0px">
        <el-upload
            class="upload-demo"
            action="http://localhost:8080/boot/files/upload"
            :multiple="false"
            :limit="1"
            :show-file-list="false"
            :on-success="fileLoad"
        >
          <el-button type="primary" plain>上传图片</el-button>

        </el-upload>

      </div>
      <a :href="img">
        <el-button type="primary" plain
                   style="height: 20px;vertical-align: top" @click="downloadFile">下载上一张</el-button>
      </a>
      <div style="display: inline-block;margin: 0 20px;vertical-align: top">

        <el-button type="primary" plain @click="addUser()">添加用户</el-button>
      </div>
    </div>


    <el-input v-model="inputText" placeholder="搜索用户" clearable
              style="width: 400px;margin: 10px 8px 0 28%;vertical-align: top">
      <template #prefix>
        <el-icon class="el-input__icon">
          <IocSearch/>
        </el-icon>
      </template>
    </el-input>
    <el-button style="vertical-align: top;margin-top: 10px" type="primary" plain
               @click="selectUserName(currentPage,inputText)">搜索
    </el-button>

    <el-table :data="tableData" style="width: 100%;margin: 20px" stripe border>

      <!--      <el-table-column prop="id" label="ID"/>-->
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="nickName" label="昵称"/>
      <el-table-column prop="age" label="年龄"/>
      <el-table-column prop="sex" label="性别"/>
      <el-table-column prop="address" label="地址"/>

      <el-table-column align="center" label="操作">

        <template #default="scope">  <!--这个scope对象，在这个组件内部都可以使用-->
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>

          <el-popconfirm title="确认删除吗?" @confirm="deleteUser(deleteData)">
            <template #reference>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-popconfirm>

        </template>

      </el-table-column>
    </el-table>


    <div style="text-align: center">
      <el-pagination background layout="prev, pager, next"
                     :total="total" :default-page-size="4"
                     v-model:current-page="currentPage">
      </el-pagination>
    </div>

  </div>


  <el-dialog v-model="dialogTableVisible" title="注册用户"
             :append-to-body="false">

    <el-form ref="form" :model="User" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="User.username"></el-input>
      </el-form-item>

      <el-form-item label="昵称">
        <el-input v-model="User.nickName"></el-input>
      </el-form-item>

      <el-form-item label="性别">
        <el-radio v-model="User.sex" label="男" style="margin-left: 40px">男</el-radio>
        <el-radio v-model="User.sex" label="女">女</el-radio>
      </el-form-item>

      <el-form-item label="年龄">
        <el-input v-model="User.age"></el-input>
      </el-form-item>

      <el-form-item label="地址">
        <el-input type="textarea" v-model="User.address"></el-input>
      </el-form-item>

      <el-button @click="resetForm" style="margin-left: 300px">取消</el-button>
      <el-button type="primary" @click="submitForm">添加</el-button>

    </el-form>
  </el-dialog>

</template>

<script>
import request from "../utils/request"
import {Search as IocSearch} from '@element-plus/icons'
import {ElMessage} from "element-plus";

export default {
  name: 'Home',
  data() {
    return {
      tableData: [],//请求获取到的数据
      inputText: "",//搜索框中的数据
      currentPage: 1,//当前页
      total: 0,//数据总条数
      dialogTableVisible: false,//添加框的显示与隐藏
      massages: {
        massageDefault: '',//默认灰色
        massageSuccess: 'success',//成功绿色
        massageWarning: 'warning',//警告黄色
        // 红色错误，不使用第二个参数即可
      },//定义顶部弹窗的四种状态
      deleteData: {},//删除按钮绑定的数据
      User: {
        id: "",
        username: "",
        nickName: "",
        age: "",
        sex: "",
        address: "",
        password: "12456"
      },//添加框中form表单中的数据
      img: "javascript:;",
    }
  },
  components: {
    IocSearch
  },
  watch: {
    currentPage: {
      handler(a) {
        this.getData(a, "")//监视属性进行分页
      }
    },
    visible: {
      handler(a, b) {
        console.log("22222")
      }
    }
  },
  methods: {


    //提示栏函数
    open(massage, type) {

      if (type) {
        ElMessage({
          message: massage,
          type: type,
        })
      } else {
        ElMessage.error(massage)
        /**
         * this.$nextTick(()=>{//将回调延迟到下一次DOM跟新之后
         * this.$refs['upload'].clearFiles()//清除文件上传列表
         * })
         */
      }
    },

    //文件下载
    downloadFile() {
      if (this.img === "javascript:;") {
        this.open("请先进行上传文件")
      }
    }
    ,
    //文件上传成功回调
    fileLoad(res) {
      this.open("上传成功", this.massages.massageSuccess);
      this.img = res.data
    }
    ,
    handleEdit(_, row) {
      //深拷贝，防止修改到真正的数据
      this.User = JSON.parse(JSON.stringify(row))
      //开启下拉框
      this.dialogTableVisible = true;
    },
    handleDelete(_, row) {
      this.deleteData = row
    },
    deleteUser(user) {
      request.delete(`http://localhost:8080/boot/user/${user.id}`).then(res => {
        this.getData(this.currentPage, "")
        this.open("删除成功", this.massages.massageSuccess)
      }).catch(err => {
        this.open("删除失败")
      })
    },
    //增加
    addUser() {
      this.dialogTableVisible = true
      this.User = {}
    },
    //表单取消按钮
    resetForm() {
      this.dialogTableVisible = false
      this.User = {}
    },
    //表单提交
    submitForm() {

      //判断id是不是null，如果是，就是post添加，不是就发送put更新请求
      // Object.keys(res.result.userInfo.extension).length == 0
      if (!this.User.id) {
        request.post("http://localhost:8080/boot/user", this.User)
            .then(res => {
              //提示弹窗
              this.open("添加成功", this.massages.massageSuccess)
              //清空数据
              this.User = {}
              //关闭
              this.dialogTableVisible = false
              //跟新
              this.getData(1, "")
            }).catch(reason => {

          this.open("添加失败，请稍后重试")

        })
      } else {
        request.put("http://localhost:8080/boot/user", this.User)
            .then(res => {

              this.open("修改成功", this.massages.massageSuccess)
              this.User = {}
              this.dialogTableVisible = false
              this.getData(1, "")
            }).catch(reason => {

          this.open("修改失败，请稍后重试")
        })

      }
    },
    //获取数据函数  当前页，输入框内容
    getData(currentPage, inputText) {

      request.get(`http://localhost:8080/boot/user?pn=${currentPage}&str=${inputText}`
          //get请求，也可以继续使用对象形式传参，
          // 但是要在对象中在添加一个配置项，再在配置项中配置参数
          /**
           * {
           *    params: {
           *      参数：参数
           *      参数：参数
           *    }
           *  }
           *
           **/
      )
          .then(res => {
            this.tableData = res.data.list

            this.total = res.data.total

          }).catch(err => {
        this.open("数据获取失败")
      })
    },

    //搜索用户
    selectUserName(currentPage, inputText) {

      this.getData(currentPage, inputText)
    }

  },

  mounted() {
    this.getData(this.currentPage, this.inputText)
  }

}
</script>
<style lang="less">

</style>
